import React, { Component } from 'react'
/*
   一、受控组件的基本使用步骤
   1、定义一个状态
   this.state={
        username:''
   }
   2、在表单项控件中定义value属性，然后将state中的变量赋值给控件的value
   <input type="text" id='username' value={this.state.username}/>
   3、在表单控件中添加onChange事件,然后在调用方法中将表单的数据通过setState完成数据更新

*/
export default class ControlledCom extends Component {
  constructor(){
    super()
    this.state={
        username:'',
        password:'',
        passwordMsg:''
    }
  }
  handleUserName=(e)=>{
    this.setState({
        username:e.target.value
    })
  }
  handlePwd=(e)=>{
    
    let pwd=e.target.value.toLowerCase()
    let pwdReg=/^[a-z0-9_]{6,12}$/
    if(pwdReg.test(pwd)){
        this.setState({
            passwordMsg:'密码正常'
        })
        this.setState({
            password:pwd
        })
    }else{
        this.setState({
            password:pwd
        })
        this.setState({
            passwordMsg:'密码有误'
        }) 
    }
   
  }
  render() {
    const {username,password,passwordMsg}=this.state
    return (
      <div>
        <h1>受控组件</h1>
         <div>
            <label htmlFor="username">姓名：</label>
            <input type="text" id='username' value={username} onChange={this.handleUserName}/>
         </div>
         <div>
            <label htmlFor="password">密码</label>
            <input type="text" id='password' value={password} onChange={this.handlePwd}/>
            <span>{passwordMsg}</span>
         </div>
      </div>
    )
  }
}
